<template>
  <div class="normalMaintenanceStandardDetails h100">
    <editPageNew
      ref="editPage"
      v-show="!showMatter"
      :rightBtnArr="rightBtnArr"
      :creatInfo="formData"
      :moreBtnArr="moreBtnArr"
      :showMore="true"
      showTopTitle
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        {{ pageType }}
      </template>
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title">
            <span class="titleLine"></span>
            值班地点
          </template>
          <editForm
            :formConfig="locationConfig"
            :formData="formData"
          ></editForm>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template slot="title">
            <span class="titleLine"></span>
            本值信息
          </template>
          <editForm
            :formConfig="currentShiftConfig"
            :formData="shiftData"
          ></editForm>
        </el-collapse-item>
        <el-collapse-item name="3">
          <template slot="title">
            <span class="titleLine"></span>
            下值信息
          </template>
          <editForm
            :formConfig="nextShiftConfig"
            :formData="nextShiftData"
          ></editForm>
        </el-collapse-item>
        <el-collapse-item name="4">
          <template slot="title">
            <span class="titleLine"></span>
            未完成工作
          </template>
          <workerInfo :tableData="formData.workCompletions" :status="0" />
        </el-collapse-item>
        <el-collapse-item name="5">
          <template slot="title">
            <span class="titleLine"></span>
            交接事项
          </template>
          <handoverMatter
            ref="handoverMatter"
            :tableData="formData.tips"
            :tipParams="tipParams"
            :shiftId="formData.id"
            :status="matterStatus"
            @showMatterPage="showMatterPage"
          />
        </el-collapse-item>
        <el-collapse-item name="6">
          <template slot="title">
            <span class="titleLine"></span>
            已完成工作
          </template>
          <workerInfo :tableData="formData.workCompletions" :status="1" />
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <editPageNew
      ref="matterPage"
      :showClose="false"
      :rightBtnArr="matterBtnArr"
      v-if="showMatter"
      showTopTitle
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        交接班配置
      </template>
      <matterList :shiftId="formData.id"></matterList>
    </editPageNew>
    <dialogPublic
      :title="title"
      :show.sync="show"
      @doSubmit="shiftConfirm"
      width="30%"
      :btnText="['提交', '取消']"
      height="100px"
      @doClose="() => (show = false)"
    >
      <div class="content">
        <div class="member">
          <div
            v-for="(item, index) in memberList"
            :key="index"
            class="memberItem"
          >
            <el-row>
              <el-col :span="6"
                ><span>{{ item.memberType }}</span></el-col
              >
              <el-col :span="12"
                ><span>{{ item.name }}</span
                ><span v-if="item.isSign" class="signed">(已签名)</span
                ><span v-else class="unSign">(未签名)</span></el-col
              >
              <el-col :span="6"
                ><el-button
                  v-if="!item.isSign"
                  size="mini"
                  type="primary"
                  @click="doSign(item, index)"
                  >签名</el-button
                ></el-col
              >
            </el-row>
          </div>
        </div>
      </div>
    </dialogPublic>
    <dialogPublic
      title="人员调整记录"
      :show.sync="showAdjuct"
      :noFootBtn="true"
    >
      <shift-record :tableData="thisAdjustRecords" title="本值"></shift-record>
      <shift-record
        style="margin-top: 20px"
        :tableData="nextAdjustRecords"
        title="下值"
      ></shift-record>
    </dialogPublic>
    <signature
      v-if="showSign"
      :showSignature.sync="showSign"
      :account="currentAccount"
      @doSign="signSucced"
    />
  </div>
</template>
<script>
import {
  queryShiftRecordDetail,
  addOrUpdateShiftRecord,
  queryAdjustRecords,
  handoverShift,
  acceptShift,
  rejectShift,
  previewShift,
} from "@/api/operationManagement/handoverManagement.js";
import { queryOldStatusList } from "@/api/operationManagement/runLog.js";
import workerInfo from "./workerInfo";
import handoverMatter from "./handoverMatter.vue";
import signature from "@/components/signature.vue";
import shiftRecord from "./shiftRecord";
import matterList from "./matterList.vue";
export default {
  components: {
    workerInfo,
    handoverMatter,
    signature,
    shiftRecord,
    matterList,
  },
  data() {
    return {
      thisAdjustRecords: [],
      nextAdjustRecords: [],
      showMatter: false,
      memberList: [],
      tipParams: {},
      title: "",
      show: false,
      showAdjuct: false,
      showSign: false,
      currentAccount: "",
      currentMemberIndex: null,
      matterStatus: 0, //交接事项的状态
      activeNames: ["1", "2", "3", "4", "5", "6"],
      moreBtnArr: [
        {
          text: "人员调整记录",
          methods: () => {
            this.getAdjustaffRecord();
            this.showAdjuct = true;
          },
        },
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ],
      matterBtnArr: [
        {
          text: "返回",
          icon: "el-icon-back",
          methods: () => {
            let query = {
              thisShiftId: this.formData.thisShiftId,
              nextShiftId: this.formData.nextShiftId,
            };
            this.getDetails(query);
            this.showMatter = false;
          },
        },
      ],
      pageType: "交班",
      hideBtn: false,
      locationConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "值班单位",
            prop: "deptName",
            type: "text", //类型
            disabled: true,
            span: 8,
          },
          {
            label: "值班地点",
            prop: "locationName",
            disabled: true,
            type: "text",
            span: 8,
          },
        ],
      },
      currentShiftConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "本值班次",
            prop: "name",
            type: "text", //类型
            disabled: true,
            span: 8,
          },
          {
            label: "本值开始时间",
            prop: "startTime",
            disabled: true,
            type: "text",
            span: 8,
          },
          {
            label: "本值结束时间",
            prop: "endTime",
            disabled: true,
            type: "text",
            span: 8,
          },
          {
            label: "本值人员",
            prop: "member",
            disabled: true,
            type: "text",
            span: 8,
          },
          {
            label: "本值交班时间",
            prop: "thisTime",
            disabled: true,
            type: "text",
            span: 8,
          },
        ],
      },
      nextShiftConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "下值班次",
            prop: "name",
            type: "text", //类型
            disabled: true,
            span: 8,
          },
          {
            label: "下值开始时间",
            prop: "startTime",
            disabled: true,
            type: "text",
            span: 8,
          },
          {
            label: "下值结束时间",
            prop: "endTime",
            disabled: true,
            type: "text",
            span: 8,
          },
          {
            label: "下值人员",
            prop: "member",
            disabled: true,
            type: "text",
            span: 8,
          },
          {
            label: "下值接班时间",
            prop: "nextTime",
            disabled: true,
            type: "text",
            span: 8,
          },
        ],
      },
      formData: {},
      shiftData: {},
      nextShiftData: {},
      disableHandover: false,
      remainingTime: "",
      timerInterval: null,
      time: 10,
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "交班确认",
          icon: "el-icon-check",
          hide: ["接班", "交接班记录", "补录"].includes(this.pageType),
          disabled: this.disableHandover,
          content: `${this.remainingTime}`,
          methods: () => {
            this.confirmHandover();
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide: ["接班", "交接班记录"].includes(this.pageType),
          methods: () => {
            this.save();
          },
        },
        {
          text: "接班确认",
          icon: "el-icon-check",
          hide: ["交班", "交接班记录", "补录"].includes(this.pageType),
          methods: () => {
            this.confirmSucceed();
          },
        },
        {
          text: "驳回",
          icon: "el-icon-check",
          hide: ["交班", "交接班记录", "补录"].includes(this.pageType),
          methods: () => {
            this.reject();
          },
        },
        {
          text: "打印",
          icon: "el-icon-printer",
          hide: ["交班", "接班", "补录"].includes(this.pageType),
          methods: () => {
            this.print();
          },
        },
      ];
      return arr;
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    //初始化详情页
    init() {
      let { shiftId, nextShiftId, pageType } = this.$route.query;
      this.pageType = pageType;
      let params = {
        thisShiftId: shiftId,
        nextShiftId: nextShiftId,
      };
      switch (pageType) {
        case "交班":
          this.matterStatus = 0;
          break;
        case "接班":
          this.matterStatus = 1;
          break;
        case "交接班记录":
          this.matterStatus = 1;
          break;
        default:
          this.matterStatus = 2;
          break;
      }
      this.getDetails(params);
      if (["query", "detail"].includes(pageType)) {
        this.hideBtn = true;
      }
    },
    //获取标准详情
    getDetails(params) {
      queryShiftRecordDetail(params).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          this.allowTime();
          this.formData.workCompletions = this.formData.workCompletions || [];
          this.shiftData = res.data.thisShift;
          this.$set(this.shiftData, "thisTime", res.data.thisTime);
          this.$set(
            this.shiftData,
            "member",
            this.handleMemberInfo(this.shiftData.staffs)
          );
          this.nextShiftData = res.data.nextShift;
          this.nextShiftData = res.data.nextShift;
          this.$set(this.nextShiftData, "nextTime", res.data.nextTime);
          this.$set(
            this.nextShiftData,
            "member",
            this.handleMemberInfo(this.nextShiftData.staffs)
          );
          this.tipParams = {
            deptId: this.formData.deptId,
            locationId: this.formData.locationId,
            staffType: this.formData.staffType,
          };
        }
      });
    },
    showMatterPage(val) {
      this.showMatter = val;
    },
    //处理人员数据
    handleMemberInfo(data) {
      let str = "";
      data.forEach((item) => {
        if (item.type == "0") {
          str += item.staffName + "|";
        } else {
          str += item.staffName + ",";
        }
      });
      str = str.slice(0, str.length - 1);
      return str;
    },
    //获取人员调整记录
    getAdjustaffRecord() {
      let params = {
        thisShiftId: this.formData.thisShift.id,
        nextShiftId: this.formData.nextShift.id,
      };
      queryAdjustRecords(params).then((res) => {
        if (res.code == 200) {
          if (res.data.thisAdjustRecords) {
            this.thisAdjustRecords = res.data.thisAdjustRecords;
          }
          if (res.data.nextAdjustRecords) {
            this.nextAdjustRecords = res.data.nextAdjustRecords;
          }
        }
      });
    },
    //允许交班时间
    allowTime() {
      this.handoverTime =
        new Date(this.formData.thisShift.endTime).getTime() -
        new Date(this.formData.advanceTime).getTime();
      //this.handoverTime = new Date("2022-05-11 19:30:00").getTime()
      let currentTime = this.$utils.getCurrentTime();
      if (this.handoverTime < currentTime) {
        this.disableHandover = false;
      } else {
        this.disableHandover = true;
        this.timerInterval = setInterval(() => {
          this.computedTime();
        }, 1000);
      }
    },
    //计算时间
    computedTime() {
      let currentTime = this.$utils.getCurrentTime();
      let times = (this.handoverTime - currentTime) / 1000; // times是剩余时间总的秒数
      let h = parseInt((times / 60 / 60) % 24); //时
      h = h < 10 ? "0" + h : h; //不足补0
      let m = parseInt((times / 60) % 60); // 分
      m = m < 10 ? "0" + m : m;
      let s = parseInt(times % 60); // 当前的秒
      s = s < 10 ? "0" + s : s;
      this.remainingTime = `${h}:${m}:${s}`;
      if (times <= 0) {
        this.disableHandover = false;
        clearInterval(this.timerInterval);
      }
    },
    //保存交班记录
    async save() {
      try {
        let params = Object.assign({}, this.formData);
        let data = this.$refs.handoverMatter.getTableData();
        params.tips = data;
        let res = await addOrUpdateShiftRecord(params);
        this.$message.success(res.description);
        if (this.pageType == "补录") {
          this.$utils.addOperateLog(this.formData.id, "补录了交接班记录");
        } else {
          this.$utils.addOperateLog(this.formData.id, "修改了交班信息");
        }
        let query = {
          thisShiftId: this.formData.thisShiftId,
          nextShiftId: this.formData.nextShiftId,
        };
        this.getDetails(query);
      } catch (error) {
        console.log(error);
      }
    },
    //确认交班
    async confirmHandover() {
      let res = await queryOldStatusList({
        confirmDeptManage: this.$store.getters.currentOrgInfo.id,
        confirmDeptManageName: this.$store.getters.currentOrgInfo.name,
        isConfirm: [0],
      });
      let logNum = res.data.total;
      if (logNum > 0) {
        this.$confirm("当前存在未确认的开停机日志，建议确认后再交班", "", {
          confirmButtonText: "继续交班",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.title = "确认交班";
            if (this.memberList.length == 0) {
              this.memberList = this.formData.thisShift.staffs.map((item) => {
                let obj = {
                  memberType: this.$store.getters.fineDirtDataName(
                    "operation_duty_type",
                    item.type
                  ),
                  name: item.staffName,
                  account: item.staffBy,
                  isSign: false,
                };
                return obj;
              });
            }
            this.show = true;
          })
          .catch(() => {});
      } else {
        this.title = "确认交班";
        if (this.memberList.length == 0) {
          this.memberList = this.formData.thisShift.staffs.map((item) => {
            let obj = {
              memberType: this.$store.getters.fineDirtDataName(
                "operation_duty_type",
                item.type
              ),
              name: item.staffName,
              account: item.staffBy,
              isSign: false,
            };
            return obj;
          });
        }
        this.show = true;
      }
    },
    //确认接班
    async confirmSucceed() {
      this.title = "确认接班";
      this.memberList = this.formData.nextShift.staffs.map((item) => {
        let obj = {
          memberType: this.$store.getters.fineDirtDataName(
            "operation_duty_type",
            item.type
          ),
          name: item.staffName,
          account: item.staffBy,
          isSign: false,
        };
        return obj;
      });
      this.show = true;
    },
    //点击签名
    doSign(item, index) {
      this.currentMemberIndex = index;
      this.currentAccount = item.account;
      this.showSign = true;
    },
    //登录验证结果
    signSucced(data) {
      this.memberList[this.currentMemberIndex].isSign = true;
    },
    //签名是否全部验证完毕
    isSignComplete() {
      return this.memberList.every((item) => {
        return item.isSign == true;
      });
    },
    //签名验证提交
    async shiftConfirm() {
      if (this.isSignComplete()) {
        if (this.title == "确认交班") {
          let params = Object.assign({}, this.formData);
          let data = this.$refs.handoverMatter.getTableData();
          params.tips = data;
          let res = await handoverShift(params);
          this.$message.success(res.description);
          this.$utils.addOperateLog(this.formData.id, "确认交班");
          this.updateListData();
          this.$refs.editPage.closePage(500);
        } else {
          let res = await acceptShift({ recordId: this.formData.id });
          this.$message.success(res.description);
          this.$utils.addOperateLog(this.formData.id, "确认接班");
          this.updateListData();
          this.$refs.editPage.closePage(500);
        }
      } else {
        this.$alert("请确保所有人员完成签名", "", {
          confirmButtonText: "确定",
          center: true,
        });
      }
    },
    //接班驳回
    async reject() {
      let res = await rejectShift({ recordId: this.formData.id });
      this.$message.success(res.description);
      this.$utils.addOperateLog(this.formData.id, "驳回了交班");
      this.updateListData();
      this.$refs.editPage.closePage(500);
    },
    //打印页面
    print() {
      let param = {
        thisShiftId: this.formData.thisShift.id,
        recordId: this.formData.id,
        nextShiftId: this.formData.nextShift.id,
      };
      const { href } = this.$router.resolve({
        name: "handoverPrint",
        query: param
      })
      window.open(href, "_blank")
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.normalMaintenanceStandardDetails {
  // overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
  .content {
    height: 200px;
    position: relative;
    .member {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      .memberItem {
        width: 300px;
        height: 40px;
        line-height: 40px;
        .unSign {
          color: #f59a23;
        }
        .signed {
          color: #aed670;
        }
        .signBtn {
          color: white;
          background-color: #2c77f4;
        }
      }
    }
  }
}
</style>
